<template>
  <el-card class="my-card">
    <div class="card-content">
      <div ref="chart" class="my-chart" />
    </div>
  </el-card>
</template>

<script lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from "echarts";

interface Props {
  title?: string;
  value?: number;
  min?: number;
  max?: number;
  unit?: string;
}

export default {
  props: {
    title: {
      type: String,
      default: "Value"
    },
    value: {
      type: Number,
      default: 0
    },
    min: {
      type: Number,
      default: 0
    },
    max: {
      type: Number,
      default: 100
    },
    unit: {
      type: String,
      default: ""
    }
  },

  setup(props: Props) {
    const chartRef = ref<HTMLElement | null>(null);

    const renderChart = () => {
      const chart = echarts.init(chartRef.value!);
      chart.setOption({
        tooltip: {
          formatter: "{a} <br/>{b} : {c}%"
        },
        series: [
          {
            name: props.title,
            type: "gauge",
            center: ["50%", "50%"],
            min: props.min,
            max: props.max,
            progress: {
              show: true
            },
            detail: {
              valueAnimation: true,
              formatter: `{value} ${props.unit}`
            },
            data: [
              {
                value: props.value,
                name: props.title
              }
            ],
            radius: "70%"
          }
        ]
      });
    };

    const handleResize = () => {
      nextTick(() => {
        echarts.getInstanceByDom(chartRef.value!).resize();
      });
    };

    onMounted(() => {
      renderChart();
      window.addEventListener("resize", handleResize);
    });

    onUnmounted(() => {
      window.removeEventListener("resize", handleResize);
    });

    return {
      chartRef
    };
  }
};
</script>

<style scoped>
.my-card {
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-content {
  width: 80%;
  height: 400px;
}

.my-chart {
  width: 100%;
  height: 100%;
}
</style>
